var aLevel = ["", "Not registered", "Not confirmed", "Customer", "Manager", "Administrator"];
var uGroup = ["", "Not registered", "Basic", "VIP"];

$(document).ready(function(){
    $('#results').hide();
	$('#right-preloader').hide();
});


function displayTable(data)
{
	$('#results-count').empty();
	$("#b-block").hide();
	$("#b-unblock").hide();
	$("#b-delete").hide();
    var totalCount = data.userlist.length;
    var userTable = $('#result-table');
    userTable.empty();
	userTable.hide();
	if (totalCount > 0)
	{
		//HEAD OF THE TABLE
		var rowstring = '<thead><tr id="result-head">';
		rowstring+='<th><input type="checkbox" id="main_checkbox" onClick="javascript:MainCheckBox()"></th>';
		rowstring+='<th>'+ "Login" +'</th>';
		rowstring+='<th>'+ "Name" +'</th>';
		rowstring+='<th>'+ "Surname" +'</th>';
		rowstring+='<th>'+ "User group" +'</th>';
		rowstring+='<th>'+ "Access level" +'</th>';
		rowstring+='<th>'+ "Phone" +'</th>';
		rowstring+='<th>'+ "Birthdate" +'</th>';
		rowstring+='<th>'+ "Blocked" +'</th>';
		rowstring+='</tr></thead>';
		userTable.append(rowstring);
		var elem = document.getElementById('result-head');
		elem.style.background = 'white';
		//BODY OF THE TABLE
		userTable.append('<tbody id="result_body">');
		$.each(data.userlist, function (index, element)
		{
			var checkboxId = "ch" + element.id.toString();
			var blId = "bl" + element.id.toString();
			var blockedValue = (element.blocked == 0 ? "no" : "yes");
			var ugValue = uGroup[element.groupId.value];
			var alValue = aLevel[element.accessLevelId.value];
			var tLogin = element.login;
			if (tLogin.length > 20) tLogin = tLogin.substring(0,19);
			var tName = element.name;
			if (tName && tName.length > 10) tName = tName.substring(0,9);
			var tSurname = element.surname;
			if (tSurname && tSurname.length > 10) tSurname = tSurname.substring(0,9);
			rowstring = "";
			rowstring += '<tr name="row_user" id='+element.id.toString()+'>';
			rowstring += '<td><input type="checkbox" name="checkboxes" id='+checkboxId+' onclick="javascript:updateMainCheckBox()" ></td>';
			rowstring += '<td>' + tLogin + '</td>';
			rowstring += '<td>' + tName + '</td>';
			rowstring += '<td>' + tSurname + '</td>';
			rowstring += '<td>' + ugValue + '</td>';//usergroup
			rowstring += '<td>' + alValue + '</td>';//user access level
			rowstring += '<td>' + element.phone + '</td>';
			rowstring += '<td>' + element.birthdate + '</td>';
			rowstring += '<td id='+blId+'>' + blockedValue + '</td>';
			rowstring += '</tr>';
			userTable.append(rowstring);
		});
		userTable.append('</tbody>');
		//PAGING
		pager = new Pager('result_body', 10, 'pager', 'pageNavPosition');
		pager.init();
		pager.showPage(1);
		//BUTTONS
		$("#b-block").show();
		$("#b-unblock").show();
		$("#b-delete").show();
		$('#results-count').append(totalCount + " users found.");
	}
	else
	{
		$('#results-count').append("no users found.");
	}
	$('#results').show();
	$('#right-preloader').hide();
	userTable.show();
}

function blockUsers()
{
    var array = document.getElementsByName("row_user");
    var res = [];
    var k = 0;
    $.each(array, function(index, value) {
        var checkboxId = "ch" + value.id;
        if ($('#'+checkboxId).prop('checked') == true)
        {
            res[k++] = value.id;
        }
    });
    doBlockUsers(res);
}

function unblockUsers()
{
    var array = document.getElementsByName("row_user");
    var res = [];
    var k = 0;
    $.each(array, function(index, value) {
        var checkboxId = "ch" + value.id;
        if ($('#'+checkboxId).prop('checked') == true)
        {
            res[k++] = value.id;
        }
    });
    doUnblockUsers(res);
}

function deleteUsers()
{
    var array = document.getElementsByName("row_user");
    var res = [];
    var k = 0;
    $.each(array, function(index, value) {
        var checkboxId = "ch" + value.id;
        if ($('#'+checkboxId).prop('checked') == true)
        {
            res[k++] = value.id;
        }
    });
    doDeleteUsers(res);
}

function doDeleteUsers(ids)
{
	$('#right-preloader').show();
	for (var i = 0; i < ids.length; i++)
	{
		var id = ids[i];
		$.ajax(
		{
			url: "dashboard",
			type: "POST",
			async: false,
			data: {
				action: "deleteUser",
				id: id
			},
			success: function(data) {
				$('#'+id).css('background',"#FE6767");
				$('#'+id).attr('name','deleted');
				$('#ch'+id).prop('name','deleted_checkbox');
				$('#ch'+id).removeAttr('checked');
				$('#ch'+id).prop('disabled','true');
			}
		});
	}
	$('#right-preloader').hide();
	updateMainCheckBox();
}

function doBlockUsers(ids)
{
	$('#right-preloader').show();
	for (var i = 0; i < ids.length; i++)
	{
		var id = ids[i];
		var blId = "bl"+id;
		if ($('#'+blId).html() == "no")
		{
			$.ajax(
			{
				url: "dashboard",
				type: "POST",
				async: false,
				data: {
					action: "changeBlockedStatus",
					id: id
				},
				success: function(data) {
					$('#'+blId).html("yes");
				}
			});
		}
	}
	$('#right-preloader').hide();
}

function doUnblockUsers(ids)
{
	$('#right-preloader').show();
	for (var i = 0; i < ids.length; i++)
	{
		var id = ids[i];
		var blId = "bl"+id;
		if ($('#'+blId).html() == "yes")
		{
			$.ajax(
			{
				url: "dashboard",
				type: "POST",
				async: false,
				data: {
					action: "changeBlockedStatus",
					id: id
				},
				success: function(data) {
					$('#'+blId).html("no");
				}
			});
		}
	}
	$('#right-preloader').hide();
}

function getUsers(page)
{
	$('#right-preloader').show();
	$.post('dashboard',
	{
		action: "getUserList",
		login : $('#login').val(),
		name : $('#name').val(),
		surname : $('#surname').val(),
		startdate : "",
		enddate : "",
		blocked : $('#blocked').val(),
		usergroup : $('#group').val()
	},
	function(data) {
		results = data;
		displayTable(data);
	});
}

function createUser()
{
	$('#message').stop(true,true);
	$.post("dashboard",
	{
		action: "createUser",
		login : $('#newlogin').val(),
		name : $('#newname').val(),
		surname : $('#newsurname').val(),
		birthdate : "",
		password :$('#newpassword').val(),
		phone :$('#newphone').val(),
		usergroup : $('#newgroup').val(),
		accesslevel : $('#newaccesslevel').val()
	},
	function(data) {
		if (data == "Invalid input")
		{
			$('#message').css('color','red');
			$('#message').html("Invalid input");
		}
		else
		{
			$('#message').css('color','black');
			$('#message').html("Success");
		}
		$('#message').fadeOut(5000);
	});
}

function updateMainCheckBox()
{
	var checkboxes = document.getElementsByName("checkboxes");
	var on = 0, total = checkboxes.length;
	$.each(checkboxes, function(index, element) {
		if ($(element).prop('checked') == true)
			++on;
	});
	var mainCheckbox = $('#main_checkbox');
	if (on == total)
	{
		mainCheckbox.css('opacity','1.0');
		mainCheckbox.attr('checked','true');
	}
	else if (on == 0)
	{
		mainCheckbox.css('opacity','1.0');
		mainCheckbox.removeAttr('checked');
	}
	else
	{
		mainCheckbox.css('opacity','0.5');
		mainCheckbox.attr('checked','true');
	}
}

function MainCheckBox()
{
	var mainCheckbox = $('#main_checkbox');
	var result;
	if (mainCheckbox.prop('checked') == true || mainCheckbox.css('opacity') == '0.5')
	{
		result = true; 
		mainCheckbox.css('opacity','1.0');
		mainCheckbox.attr('checked', 'true');
	}
	else
	{
		result = false;
		mainCheckbox.removeAttr('checked');	
	}
	$.each(checkboxes, function(index, element) {
		if (result == true)
			$(element).attr('checked','true');
		else
			$(element).removeAttr('checked');
	});
}